// src/main.js
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'
import router from './router' 
import './mock'

const app = createApp(App)

app.use(ElementPlus)
app.use(router)

// 自定义指令集合
const directives = {
  // 调试用自定义指令
  custom: {
    beforeMount(el, binding) {
      console.log('custom beforeMount', { el, binding })
    },
    mounted(el, binding) {
      console.log('custom mounted', { el, binding })
    },
    beforeUpdate(el, binding, vnode) {
      console.log('custom beforeUpdate', { el, binding, vnode })
    },
    updated(el, binding, vnode) {
      console.log('custom updated', { el, binding, vnode })
    },
    beforeUnmount() {
      console.log('custom beforeUnmount')
    },
    unmounted() {
      console.log('custom unmounted')
    }
  },

  // 简易focus指令
  focus: (el, binding) => {
    console.log('focus directive:', { el, binding })
    el.focus()
  },

  // 防抖指令优化版
  debounce: {
    mounted(el, binding) {
      let timeout = null
      const eventType = binding.arg || 'input'  // 支持指定事件类型
      const delay = parseInt(binding.value?.delay) || 500

      const handler = () => {
        binding.value?.handler?.()
      }

      el._debounceHandler = handler
      
      el.addEventListener(eventType, () => {
        clearTimeout(timeout)
        timeout = setTimeout(el._debounceHandler, delay)
      })
    },
    unmounted(el) {
      el.removeEventListener('input', el._debounceHandler)
    }
  },

  // 输入限制指令
  limit: {
    mounted(el, binding) {
      const limit = parseInt(binding.arg) || 10
      const handleInput = () => {
        if (el.value.length > limit) {
          el.value = el.value.slice(0, limit)
          el.dispatchEvent(new Event('input')) // 触发数据更新
        }
      }
      
      el._limitHandler = handleInput
      el.addEventListener('input', handleInput)
    },
    unmounted(el) {
      el.removeEventListener('input', el._limitHandler)
    }
  },

  // 权限指令增强版
  permission: {
    mounted(el, binding) {
      const { value: role } = binding
      const buttonType = el.textContent.trim()
      
      const isAdmin = role === 'admin'
      const isTeacher = role === 'teacher'
      
      // 权限判断逻辑
      if (!isAdmin && !isTeacher) {
        if (['修改', '删除'].includes(buttonType)) {
          el.remove()
        }
      } else if (isTeacher && buttonType === '删除') {
        el.remove()
      }
    }
  }
}

// 批量注册指令
Object.entries(directives).forEach(([name, directive]) => {
  app.directive(name, directive)
})

// 挂载应用（仅保留一次）
app.mount('#app')